package org.andlisp.android;

import android.graphics.Color;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.content.Context;

public class SafePreferenceManager
{
  public static int getInt(Context context, String key, int def) {
    return getInt(PreferenceManager.getDefaultSharedPreferences(context), key, def);
  }

  public static int getInt(SharedPreferences sp, String key, int def) {
    try {
      return sp.getInt(key, def);
    } catch (Throwable t) {}
    try {
      String s = sp.getString(key, null);
      if (s != null)
        return Integer.parseInt(s);
    } catch (Throwable t) {}
    return def;
  }

  public static String getString(Context context, String key, String def) {
    return getString(PreferenceManager.getDefaultSharedPreferences(context), key, def);
  }

  public static String getString(SharedPreferences sp, String key, String def) {
    try {
      return sp.getString(key, def);
    } catch (Throwable t) {}
    return def;
  }

  public static int getColor(Context context, String key, String def) {
    return getColor(PreferenceManager.getDefaultSharedPreferences(context), key, def);
  }

  public static int getColor(SharedPreferences sp, String key, String def) {
    try {
      return Color.parseColor(sp.getString(key, def));
    } catch (Throwable t) {}
    return Color.parseColor(def);
  }

  public static boolean getBoolean(Context ctx, String key, boolean def) {
    return getBoolean(PreferenceManager.getDefaultSharedPreferences(ctx), key, def);
  }

  public static boolean getBoolean(SharedPreferences sp, String key, boolean def) {
    try {
      return sp.getBoolean(key, def);
    } catch (Throwable t) {}
    return def;
  }
}
